{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# (Frustratingly Easy) LLaVA OneVision Tutorial\n",
    "\n",
    "We know that it's always beneficial to have a unified interface for different tasks. So we are trying to unify the interface for image, text, image-text interleaved, and video input. And in this tutorial, we aim to provide the most straightforward way to use our model. \n",
    "\n",
    "We use our 0.5B version as an example. This could be running on a GPU with 4GB memory. And with the following examples, you could see it's surprisingly have promising performance on understanding the image, interleaved image-text, and video. Tiny but mighty!\n",
    "\n",
    "The same code could be used for 7B model as well.\n",
    "\n",
    "## Inference Guidance\n",
    "\n",
    "First please install our repo with code and environments: pip install git+https://github.com/LLaVA-VL/LLaVA-NeXT.git\n",
    "\n",
    "Here is a quick inference code using [lmms-lab/qwen2-0.5b-si](https://huggingface.co/lmms-lab/llava-onevision-qwen2-0.5b-si) as an example. You will need to install `flash-attn` to use this code snippet. If you don't want to install it, you can set `attn_implementation=None` when load_pretrained_model\n",
    "\n",
    "### Image Input\n",
    "Tackling the single image input with LLaVA OneVision is pretty straightforward."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llava.model.builder import load_pretrained_model\n",
    "from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token\n",
    "from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX\n",
    "from llava.conversation import conv_templates, SeparatorStyle\n",
    "\n",
    "from PIL import Image\n",
    "import requests\n",
    "import copy\n",
    "import torch\n",
    "\n",
    "import sys\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "pretrained = \"lmms-lab/llava-onevision-qwen2-0.5b-si\"\n",
    "model_name = \"llava_qwen\"\n",
    "device = \"cuda\"\n",
    "device_map = \"auto\"\n",
    "tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map)  # Add any other thing you want to pass in llava_model_args\n",
    "\n",
    "model.eval()\n",
    "\n",
    "url = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
    "image = Image.open(requests.get(url, stream=True).raw)\n",
    "image_tensor = process_images([image], image_processor, model.config)\n",
    "image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]\n",
    "\n",
    "conv_template = \"qwen_1_5\"  # Make sure you use correct chat template for different models\n",
    "question = DEFAULT_IMAGE_TOKEN + \"\\nWhat is shown in this image?\"\n",
    "conv = copy.deepcopy(conv_templates[conv_template])\n",
    "conv.append_message(conv.roles[0], question)\n",
    "conv.append_message(conv.roles[1], None)\n",
    "prompt_question = conv.get_prompt()\n",
    "\n",
    "input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
    "image_sizes = [image.size]\n",
    "\n",
    "\n",
    "cont = model.generate(\n",
    "    input_ids,\n",
    "    images=image_tensor,\n",
    "    image_sizes=image_sizes,\n",
    "    do_sample=False,\n",
    "    temperature=0,\n",
    "    max_new_tokens=4096,\n",
    ")\n",
    "text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
    "print(text_outputs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You could use the following code to make it streaming in terminal, this would be pretty useful when creating a chatbot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from threading import Thread\n",
    "from transformers import TextIteratorStreamer\n",
    "import json\n",
    "\n",
    "url = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
    "image = Image.open(requests.get(url, stream=True).raw)\n",
    "image_tensor = process_images([image], image_processor, model.config)\n",
    "image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]\n",
    "\n",
    "conv_template = \"qwen_1_5\"\n",
    "question = DEFAULT_IMAGE_TOKEN + \"\\nWhat is shown in this image?\"\n",
    "conv = copy.deepcopy(conv_templates[conv_template])\n",
    "conv.append_message(conv.roles[0], question)\n",
    "conv.append_message(conv.roles[1], None)\n",
    "prompt_question = conv.get_prompt()\n",
    "\n",
    "input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
    "image_sizes = [image.size]\n",
    "\n",
    "max_context_length = getattr(model.config, \"max_position_embeddings\", 2048)\n",
    "num_image_tokens = question.count(DEFAULT_IMAGE_TOKEN) * model.get_vision_tower().num_patches\n",
    "\n",
    "streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)\n",
    "\n",
    "max_new_tokens = min(4096, max_context_length - input_ids.shape[-1] - num_image_tokens)\n",
    "\n",
    "if max_new_tokens < 1:\n",
    "    print(\n",
    "        json.dumps(\n",
    "            {\n",
    "                \"text\": question + \"Exceeds max token length. Please start a new conversation, thanks.\",\n",
    "                \"error_code\": 0,\n",
    "            }\n",
    "        )\n",
    "    )\n",
    "else:\n",
    "    gen_kwargs = {\n",
    "        \"do_sample\": False,\n",
    "        \"temperature\": 0,\n",
    "        \"max_new_tokens\": max_new_tokens,\n",
    "        \"images\": image_tensor,\n",
    "        \"image_sizes\": image_sizes,\n",
    "    }\n",
    "\n",
    "    thread = Thread(\n",
    "        target=model.generate,\n",
    "        kwargs=dict(\n",
    "            inputs=input_ids,\n",
    "            streamer=streamer,\n",
    "            **gen_kwargs,\n",
    "        ),\n",
    "    )\n",
    "    thread.start()\n",
    "\n",
    "    generated_text = \"\"\n",
    "    for new_text in streamer:\n",
    "        generated_text += new_text\n",
    "        print(generated_text, flush=True)\n",
    "        # print(json.dumps({\"text\": generated_text, \"error_code\": 0}), flush=True)\n",
    "\n",
    "    print(\"Final output:\", generated_text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Image-Text Interleaved Input\n",
    "\n",
    "Now switching to our onevision model for more complex tasks. You should start to use `llava-onevision-qwen2-0.5b-ov` for image-text interleaved input and video input.\n",
    "\n",
    "Processing image-text interleaved input is a bit more complicated. But following the code below should work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load model\n",
    "pretrained = \"lmms-lab/llava-onevision-qwen2-0.5b-ov\"\n",
    "model_name = \"llava_qwen\"\n",
    "device = \"cuda\"\n",
    "device_map = \"auto\"\n",
    "tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map)\n",
    "\n",
    "model.eval()\n",
    "\n",
    "# Load two images\n",
    "url1 = \"https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true\"\n",
    "url2 = \"https://raw.githubusercontent.com/haotian-liu/LLaVA/main/images/llava_logo.png\"\n",
    "\n",
    "image1 = Image.open(requests.get(url1, stream=True).raw)\n",
    "image2 = Image.open(requests.get(url2, stream=True).raw)\n",
    "\n",
    "images = [image1, image2]\n",
    "image_tensors = process_images(images, image_processor, model.config)\n",
    "image_tensors = [_image.to(dtype=torch.float16, device=device) for _image in image_tensors]\n",
    "\n",
    "# Prepare interleaved text-image input\n",
    "conv_template = \"qwen_1_5\"\n",
    "question = f\"{DEFAULT_IMAGE_TOKEN} This is the first image. Can you describe what you see?\\n\\nNow, let's look at another image: {DEFAULT_IMAGE_TOKEN}\\nWhat's the difference between these two images?\"\n",
    "\n",
    "conv = copy.deepcopy(conv_templates[conv_template])\n",
    "conv.append_message(conv.roles[0], question)\n",
    "conv.append_message(conv.roles[1], None)\n",
    "prompt_question = conv.get_prompt()\n",
    "\n",
    "input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
    "image_sizes = [image.size for image in images]\n",
    "\n",
    "# Generate response\n",
    "cont = model.generate(\n",
    "    input_ids,\n",
    "    images=image_tensors,\n",
    "    image_sizes=image_sizes,\n",
    "    do_sample=False,\n",
    "    temperature=0,\n",
    "    max_new_tokens=4096,\n",
    ")\n",
    "text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
    "print(text_outputs[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Video Input\n",
    "\n",
    "Now let's try video input. It's the same as image input, but you need to pass in a list of video frames. And remember to set the `<image>` token only once in the prompt, e.g. \"<image>\\nWhat is shown in this video?\", not \"<image>\\n<image>\\n<image>\\nWhat is shown in this video?\". Since we trained on this format, it's important to keep the format consistent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llava.model.builder import load_pretrained_model\n",
    "from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token\n",
    "from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX\n",
    "from llava.conversation import conv_templates, SeparatorStyle\n",
    "\n",
    "import torch\n",
    "import cv2\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import requests\n",
    "import copy\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "# Load the OneVision model\n",
    "pretrained = \"lmms-lab/llava-onevision-qwen2-0.5b-ov\"\n",
    "model_name = \"llava_qwen\"\n",
    "device = \"cuda\"\n",
    "device_map = \"auto\"\n",
    "tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map)\n",
    "\n",
    "model.eval()\n",
    "\n",
    "\n",
    "# Function to extract frames from video\n",
    "def extract_frames(video_path, num_frames=8):\n",
    "    cap = cv2.VideoCapture(video_path)\n",
    "    frames = []\n",
    "    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n",
    "    indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)\n",
    "\n",
    "    for i in indices:\n",
    "        cap.set(cv2.CAP_PROP_POS_FRAMES, i)\n",
    "        ret, frame = cap.read()\n",
    "        if ret:\n",
    "            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
    "            frames.append(Image.fromarray(frame))\n",
    "\n",
    "    cap.release()\n",
    "    return frames\n",
    "\n",
    "\n",
    "# Load and process video\n",
    "video_path = \"jobs.mp4\"\n",
    "video_frames = extract_frames(video_path)\n",
    "image_tensors = process_images(video_frames, image_processor, model.config)\n",
    "image_tensors = [_image.to(dtype=torch.float16, device=device) for _image in image_tensors]\n",
    "\n",
    "# Prepare conversation input\n",
    "conv_template = \"qwen_1_5\"\n",
    "question = f\"{DEFAULT_IMAGE_TOKEN}\\nDescribe what's happening in this video.\"\n",
    "\n",
    "conv = copy.deepcopy(conv_templates[conv_template])\n",
    "conv.append_message(conv.roles[0], question)\n",
    "conv.append_message(conv.roles[1], None)\n",
    "prompt_question = conv.get_prompt()\n",
    "\n",
    "input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors=\"pt\").unsqueeze(0).to(device)\n",
    "image_sizes = [frame.size for frame in video_frames]\n",
    "\n",
    "# Generate response\n",
    "cont = model.generate(\n",
    "    input_ids,\n",
    "    images=image_tensors,\n",
    "    image_sizes=image_sizes,\n",
    "    do_sample=False,\n",
    "    temperature=0,\n",
    "    max_new_tokens=4096,\n",
    ")\n",
    "text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)\n",
    "print(text_outputs[0])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llava",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
